package com.hurst.autotap;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends BaseActivity{
    public static final int REQUEST_SELECT_DEVICE = 1;
    public static final int REQUEST_SELECT_PAIREDDEVICE = 2;
    TextView stateTv;
    Activity activity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        setContentView(R.layout.activity_main);
        AddFragment(savedInstanceState);
        registerReceiver(bluetoothReceiver, makePairIntentFilter());

        findViewById(R.id.connLb).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UtilCls.GetBluetoothPermission(activity)){
                    Intent newIntent = new Intent(getBaseContext(), ActivityDeviceList.class);
                    startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                }
            }
        });
        findViewById(R.id.selectbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent newIntent = new Intent(getBaseContext(), ActivityPairedDevice.class);
                startActivityForResult(newIntent, REQUEST_SELECT_PAIREDDEVICE);
            }
        });

        stateTv = findViewById(R.id.stateTv);
        CommonInterface.ConnectionStateChangeListener connectionStateChangeListener = new CommonInterface.ConnectionStateChangeListener() {
            @Override public void onConnecting() {
                runOnUiThread(new Runnable() {
                    @Override public void run() { stateTv.setText("状态:连接中..."); }
                });
            }
            @Override
            public void onConnected() {
                runOnUiThread(new Runnable() {
                    @Override public void run() { stateTv.setText("状态:已连接"); }
                });
                AquireWakeLock();
            }
            @Override
            public void onDisConnected() {
                runOnUiThread(new Runnable() {
                    @Override public void run() { stateTv.setText("状态:连接失败"); }
                });
                ReleaseWakeLock();
            }
        };

        HidUitls.connectionStateChangeListener = connectionStateChangeListener;
        HidUitls.RegistApp(getApplicationContext());
        HidConsts.reporttrans(getApplicationContext());
    }
    private void AddFragment(Bundle savedInstanceState) {
        try {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            if (savedInstanceState != null) {
                Fragment[] fragments = new Fragment[]
                        {FragmentMousePad.getInstance()};
                for (int i = 0; i < fragments.length; i++) {
                    Fragment fragment = fragmentManager.findFragmentByTag(fragments[i].getClass().getSimpleName());
                    if (null != fragment) {
                        //fragmentTransaction.hide(fragment);
                        fragmentTransaction.remove(fragment);
                    } else {
                        fragment = fragments[i];
                        fragmentTransaction.add(R.id.tabcontent, fragment, fragment.getClass().getSimpleName());
                        fragmentTransaction.hide(fragment);
                    }
                }
            }
            fragmentTransaction.add(R.id.tabcontent, FragmentMousePad.getInstance(), FragmentMousePad.class.getSimpleName());
            fragmentTransaction.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if(HidConsts.HidDevice != null) {
            HidUitls.ReConnect(this);
            HidConsts.HidDevice = HidUitls.HidDevice;
            HidConsts.BtDevice = HidUitls.BtDevice;
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case REQUEST_SELECT_DEVICE: //When the ActivityDeviceList return, with the selected device address
            case REQUEST_SELECT_PAIREDDEVICE:
                if (resultCode == Activity.RESULT_OK && data != null) {
                    String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
                    HidUitls.SelectedDeviceMac = deviceAddress;
                    if(HidUitls.Pair(deviceAddress)){
                        HidUitls.Connect(deviceAddress);
                    }
                }
                break;
            default:
                break;
        }
    }
    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            try {
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                } else if (action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
                } else if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
                    if(HidUitls.BtDevice.getBondState() == BluetoothDevice.BOND_BONDED){
                        HidUitls.Connect(HidUitls.BtDevice);
                    }else if(HidUitls.BtDevice.getBondState() == BluetoothDevice.BOND_NONE){
                    }else if(HidUitls.BtDevice.getBondState() == BluetoothDevice.BOND_BONDING){
                    }
                }
//                else if(action.equals("com.hiddroid.cmddata")){
//                    int x = intent.getIntExtra("x",0);
//                    int y = intent.getIntExtra("y",0);
//                    Log.v("u-mainactivity"," x:"+x+"  y:"+y);
//                }
            }
            catch (Exception ex){
                ex.printStackTrace();
            }
        }
    };
    private static IntentFilter makePairIntentFilter() {
        final IntentFilter filter=new IntentFilter();
        filter.addAction("android.bluetooth.device.action.FOUND");
        filter.addAction("android.bluetooth.device.action.PAIRING_REQUEST");
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

        return filter;
    }

}
